package com.enjoyor.health.HGPT.web;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

/**
 * 接受参数和返回数据打印
 * @author Zhu Min
 * @date 2023/10/18 9:39
 */
@Slf4j
@Aspect
@Component
public class RestAspectLogger {
    @Pointcut("execution(* *..rest.*Controller.*(..))")
    public void showInOrOut(){

    }

    @Before("showInOrOut()")
    public void showInputParams(JoinPoint joinPoint){
        Object[] args = joinPoint.getArgs();
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        String[] parameterNames = methodSignature.getParameterNames();
        StringBuilder paramDes = new StringBuilder();
        paramDes.append("\n类：").append(signature.getDeclaringTypeName()).
                append("中，方法：").append(methodSignature.getMethod().getName()).append("(..)被调用, 入参如下");

        for (int i = 0; i < args.length; i++){
            paramDes.append("\n").append(parameterNames[i]).append(": ").append(args[i]);
        }
        log.info(paramDes.toString());

    }

    @AfterReturning(value = "showInOrOut()" , returning = "retVal")
    public void showOutput(JoinPoint joinPoint, Object retVal){
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        StringBuilder ret = new StringBuilder();
        ret.append("\n类：").append(signature.getDeclaringTypeName()).
                append("中，方法：").append(methodSignature.getMethod().getName()).append("(..)被调用, 返回值：");
        ret.append("\n").append(retVal == null? "" : retVal.toString());
        log.info(ret.toString());
    }
}
